<?php

function rds() {
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $redis->auth('redis');
    return $redis;
}

if (isset($_GET['send'])) {
    rds()->publish('kyoChat', $_GET['send']);
    // echo $_GET['send'];
    exit(0);
}

if (isset($_GET['chat'])) {
    echo rds()->lPop('Chat');
    exit(0);
}

$html = <<< EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Redis Chat</title>
    <style>
    .chat {
        width: 80%;
        height: 200px;
        border: 1px #F00 solid;
        overflow-y: scroll;
    }
    </style>
</head>
<body>
    <div class="chat" id="chat"></div>
    <div>
    <label for="user">用户:</label>
    <input type="text" id="user" name="user" />
    </div>
    <div>
    <label for="content">内容:</label>
    <textarea id="content" name="content" cols="30" rows="5"></textarea>
    </div>
    <div><button id="send">发送</button></div>
    <script>
        var btn = document.getElementById('send');
        var chat = document.getElementById('chat');
        var user = document.getElementById('user');
        var content = document.getElementById('content');

        var xhttp = new XMLHttpRequest();

        xhttp.onreadystatechange = function() {
            if (xhttp.readyState == 4
                    && xhttp.status == 200) {
                if (xhttp.responseText.length != 0)
                    chat.innerHTML += xhttp.responseText + "<br />";
            }
        };

        btn.onclick = function() {
            if (user.value.length == 0
                    || content.value.length == 0) {
                alert('请填写用户名或内容!');
                return true;
            }
            var url = '?send="' + user.value + ": " + content.value + '"';
            console.log(url);
            xhttp.open('GET', url);
            xhttp.send();
        };

        setInterval(function(){
            xhttp.open('GET', '?chat=1');
            xhttp.send();
        }, 1000);

    </script>
</body>
</html>
EOF;

echo $html;
